#include "gameview.h"
#include "ui_gameview.h"
#include "algorithm.h"
#include <QDebug>
#include <iostream>

using namespace std;
// 颜色数组 存储2，4，8……2的17次方一共18个数的背景色
QColor digitBkg[18] = {QColor::fromRgb(245,245,220), QColor::fromRgb(240,230,140),
                            QColor::fromRgb(218,165,32), QColor::fromRgb(255,165,0),
                            QColor::fromRgb(255,215,0), QColor::fromRgb(255,69,0),
                            QColor::fromRgb(255,0,255), QColor::fromRgb(138,43,226),
                            QColor::fromRgb(65,105,225), QColor::fromRgb(0,255,255),
                            QColor::fromRgb(60,179,113),QColor::fromRgb(0,100,0),
                            QColor::fromRgb(255,20,147),QColor::fromRgb(75,0,130),
                            QColor::fromRgb(72,209,204),QColor::fromRgb(128,128,0),
                            QColor::fromRgb(178,34,34),QColor::fromRgb(255,192,203)};
GameView::GameView(QWidget *parent) :
    QWidget(parent,Qt::FramelessWindowHint),
    ui(new Ui::GameView)
{
    ui->setupUi(this);
    resize(400, 600);
    userName="sdad";
    memset(algorithm.board, 0, sizeof(algorithm.board));
    setAutoFillBackground(true);
    QPalette pal = palette();
    pal.setColor(QPalette::Background, QColor("#FAF8F0"));
    setPalette(pal);

    title = new QLabel(tr("2048"), this);
    title->setStyleSheet("color:#746D65;");
    title->setFont(QFont("arial", 30, QFont::Black));

    // 构造一个字体对象
    QFont font;
    font.setFamily("Arial");
    font.setBold(true);
    font.setPixelSize(15);
    // 构造一个标签对象
    scorelabel = new QLabel("SCORE\n0", this);
    scorelabel->setGeometry(200, 10, 60, 40);
    scorelabel->setFont(font);
    scorelabel->setAlignment(Qt::AlignCenter);
    scorelabel->setStyleSheet("QLabel{color:#FFFFEE;background:#BEAD9D}");

    name = new QLabel(this);
    name->setText(userName);    //不知道为啥显示不出来
    name->setGeometry(20,70,100,50);
    name->setFont(font);
    name->setAlignment(Qt::AlignCenter);
    name->setStyleSheet("QLabel{color:#FFFFEE;background:#BEAD9D}");

    up=new QPushButton("up",this);
    up->setFont(QFont("Arial", 10, QFont::Black));
    up->setGeometry(250, 60, 60, 30);
    connect(up, SIGNAL(clicked()), this, SLOT(gridUp()));
    up->hide();

    down=new QPushButton("down",this);
    down->setFont(QFont("Arial", 10, QFont::Black));
    down->setGeometry(250, 160, 60, 30);
    connect(down, SIGNAL(clicked()), this, SLOT(gridDown()));
    down->hide();

    left=new QPushButton("left",this);
    left->setFont(QFont("Arial", 10, QFont::Black));
    left->setGeometry(200, 110, 60, 30);
    connect(left, SIGNAL(clicked()), this, SLOT(gridLeft()));
    left->hide();

    right=new QPushButton("right",this);
    right->setFont(QFont("Arial", 10, QFont::Black));
    right->setGeometry(300, 110, 60, 30);
    connect(right, SIGNAL(clicked()), this, SLOT(gridRight()));
    right->hide();

    start=new QPushButton("start",this);
    start->setFont(QFont("Arial", 10, QFont::Black));
    start->setGeometry(40, 150, 60, 30);
    connect(start, SIGNAL(clicked()), this, SLOT(newStart()));

    resetbtn=new QPushButton("reset",this);
    resetbtn->setFont(QFont("Arial", 10, QFont::Black));
    resetbtn->setGeometry(110, 150, 60, 30);
    connect(resetbtn, SIGNAL(clicked()), this, SLOT(reset()));
    resetbtn->hide();

    closebtn = new QPushButton("x", this);
    closebtn->setFocusPolicy(Qt::NoFocus);
    closebtn->setFont(QFont("Arial", 11, QFont::Normal));
    closebtn->setStyleSheet("QPushButton{border-style:flat;color:#BDAD9F}"
                        "QPushButton:hover{border-style:flat;color:#FF0000}");
    closebtn->setCursor(Qt::PointingHandCursor);
    closebtn->setGeometry(382, 3, 15, 15);
    connect(closebtn, SIGNAL(clicked()), this, SLOT(close()));

    connect(&rankingview,&RankingView::RenewSignal,this,&GameView::dealRSignal);// 让函数去处理RenewSignal信号
    connect(&rankingview,&RankingView::ExitSignal,this,&GameView::dealESignal);// 让函数去处理ExitSignal信号
}

GameView::~GameView()
{
    delete ui;
}

void GameView::paintEvent(QPaintEvent *)
{
    QPainter painter(this); // 构造一个QPainter对象
    QBrush brush(QColor::fromRgb(141, 121, 81)); // 构造一个画刷
    painter.setBrush(brush);   // 使painter应用这个画刷
    painter.setPen(Qt::NoPen);
    painter.drawRect(2,200,396,398);//边框矩形绘制
    w =396, h = 398;
    w = (w - 25) / 4, h = (h - 25) / 4;//每个格子的长宽
       QFont font; //构造一个字体
       font.setFamily("Consolas");
       font.setBold(true);
       font.setPixelSize(30);
       painter.setFont(font);

    for (int i = 0; i < 4; i++)  //绘制游戏面板
        for (int j = 0; j < 4; j++)
        {
            if (algorithm.board[i][j])
            {
                brush.setColor(digitBkg[getBitCount(algorithm.board[i][j])]);
                painter.setBrush(brush);
                painter.drawRect(QRectF(7 + (w + 5) * j, 207 + (h + 5) * i, w, h));
                painter.setPen(QColor::fromRgb(0, 0, 0));
                painter.drawText(QRectF(7 + (w + 5) * j, 207 + (h + 5) * i, w, h), Qt::AlignCenter,
                                 QString::number(algorithm.board[i][j]));
                painter.setPen(Qt::NoPen);
            }
            else
            {
                brush.setColor(QColor::fromRgb(171, 165, 141));
                painter.setBrush(brush);
                painter.drawRect(QRectF(7 + (w + 5) * j, 207 + (h + 5) * i, w, h));
            }
        }
    name->setText(userName);
}


int GameView::getBitCount(int n)
{
    int c = 0;
    while (n >>= 1)
        c++;
    return c - 1;
}

void GameView::newStart()
{
    start->hide();
    resetbtn->show();
    up->show();
    down->show();
    left->show();
    right->show();
    memset(algorithm.board, 0, sizeof(algorithm.board));
    algorithm.clearScore();
    scoreView();
    //srand((unsigned)time(nullptr));
    int newNumber = rand()%10 < 9 ? 2 : 4;   //新随机数的值
    int changePlace = rand()%16;  //第changePlace个为0元素将会被替代

     algorithm.board[changePlace/4][changePlace%4] = newNumber;
     up->setVisible(true);
     down->setVisible(true);
     left->setVisible(true);
     right->setVisible(true);
     update();
}

void GameView::reset()
{
    memset(algorithm.board, 0, sizeof(algorithm.board));
    algorithm.clearScore();
    scoreView();
    //srand((unsigned)time(nullptr));
    int newNumber = rand()%10 < 9 ? 2 : 4;   //新随机数的值
    int changePlace = rand()%16;  //第changePlace个为0元素将会被替代

     algorithm.board[changePlace/4][changePlace%4] = newNumber;
     update();
}

void GameView::gridUp()
{
    algorithm.changMatrixUp();
    algorithm.generateRandom();
    scoreView();
    update();

    if(algorithm.sameElment() == 0)
    {
       rankingview.show();
       rankingview.score = algorithm.getScore();   //赋值分数
       rankingview.userName = userName;    //赋值用户名
       rankingview.startDis = 1;  //设定标志位
    }
}

void GameView::gridDown()
{
    algorithm.changMatrixDown();
    algorithm.generateRandom();
    scoreView();
    update();

    if(algorithm.sameElment() == 0)
    {
       rankingview.show();
       rankingview.score = algorithm.getScore();   //赋值分数
       rankingview.userName = userName;    //赋值用户名
       rankingview.startDis = 1;  //设定标志位
    }
}

void GameView::gridLeft()
{
    algorithm.changMatrixLeft();
    algorithm.generateRandom();
    scoreView();
    update();

    if(algorithm.sameElment() == 0)
    {
        rankingview.show();
        rankingview.score = algorithm.getScore();   //赋值分数
        rankingview.userName = userName;    //赋值用户名
        rankingview.startDis = 1;  //设定标志位
    }
}

void GameView::gridRight()
{
    algorithm.changMatrixRight();
    algorithm.generateRandom();
    scoreView();
    update();

    if(algorithm.sameElment() == 0)
    {
        rankingview.show();
        rankingview.score = algorithm.getScore();   //赋值分数
        rankingview.userName = userName;    //赋值用户名
        rankingview.startDis = 1;  //设定标志位
    }
}

void GameView::keyPressEvent(QKeyEvent * event)//WSAD控制方向（不知道为什么上下左右按键控制不了）
{
    switch (event->key())
       {
       case Qt::Key_W:
           gridUp();
           break;
       case Qt::Key_S:
           gridDown();
           break;
        case Qt::Key_A:
           gridLeft();
           break;
        case Qt::Key_D:
           gridRight();
           break;
       default:
           break;
       }
}

void GameView::scoreView() //分数显示
{
    scorelabel->setText(QString("Score:\n %1").arg(algorithm.getScore()));
}

void GameView::dealESignal() //全部退出
{
    rankingview.close();
    this->close();
}

void GameView::dealRSignal()//隐藏排行榜界面
{
    rankingview.hide();
    memset(algorithm.board, 0, sizeof(algorithm.board));
    algorithm.clearScore();
    scoreView();
    //srand((unsigned)time(nullptr));
    int newNumber = rand()%10 < 9 ? 2 : 4;   //新随机数的值
    int changePlace = rand()%16;  //第changePlace个为0元素将会被替代

     algorithm.board[changePlace/4][changePlace%4] = newNumber;
     update();
}

